import { loginFailPage, loginFailExportData } from '@/services/loginLog';
import moment from 'moment';

const defaultQuery = {
  appId: undefined,
  mobile: '',
  startSendTime: null,
  endSendTime: null,
};

export default {
  namespace: 'loginFailLog',

  state: {
    query: { ...defaultQuery },
    list: {
      data: [],
      pagination: {},
    },
    exporting: false,
  },

  effects: {
    *fetch({ payload }, { call, put, select }) {
      yield put({ type: 'query', payload });
      const query = yield select(state => state.loginFailLog.query);
      const { data } = yield call(loginFailPage, query);
      yield put({
        type: 'list',
        payload: {
          data: data.content,
          pagination: {
            current: data.number + 1,
            pageSize: data.size,
            total: Number(data.totalElements),
          },
        },
      });
    },
    *batchExport({ payload }, { call, put }) {
      yield put({ type: 'exporting', payload: true });
      const blob = yield call(loginFailExportData, payload);
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = `登录失败日志${moment().format('YYYYMMDDHHmmss')}.xlsx`;
      a.click();
      window.URL.revokeObjectURL(url);
      yield put({ type: 'exporting', payload: false });
    },
    *reset(_, { put }) {
      yield put({ type: 'fetch', payload: { ...defaultQuery, page: 0, size: 10 } });
    },
  },

  reducers: {
    list(state, { payload }) {
      return { ...state, list: { ...state.list, ...payload } };
    },
    query(state, { payload }) {
      return { ...state, query: { ...state.query, ...payload } };
    },
    exporting(state, { payload }) {
      return { ...state, exporting: payload };
    },
  },
};
